<style>
.pure_table_extra { width: 100%; margin-top: 5px; }
.pure_table_extra th { height: 25px; line-height: 25px; cursor: pointer; }
.pure_table_extra img { cursor: pointer; margin-right: 2px; }
.pure_table_extra td { vertical-align: middle; }
.smaller span { font-size: 11px !important; padding: 0.2em 1em !important; }
</style>

<?php
$pg = Utils::get_param('pg', 1);
$q = Utils::get_param('q', 'ASC');
$o = Utils::get_param('o', 't.name');
$search = json_decode(Utils::get_param('search', '[]'));

$opts = new stdClass();
if (isset($search->type) && isset($search->phrase)) {
  if ($search->type == 1) {
    $opts->cd = 't.status = :v1';
    $opts->cdv = array(':v1' => 1);
  } else if ($search->type == 2) {
    $opts->cd = 't.status = :v1';
    $opts->cdv = array(':v1' => 0);
  } else if ($search->type == 3) {
    $opts->cd = 't.alert__ = :v1 AND t.status = :v2';
    $opts->cdv = array(':v1' => 1, ':v2' => 1);
  }
  
  if ($search->type != 0) {
    $opts->cd .= ' AND ';
  }
  
  $opts->cd .=  '(t.name LIKE :v3)';
  $opts->cdv[":v3"] = "%$search->phrase%";
}
$data = $orm->get('pb_ecom_product', $o, $q, $pg, SIZE, $opts);

$categories = $orm->get('pb_ecom_category', 't.name', 'ASC', NULL, NULL, NULL)->d;
$brands = $orm->get('pb_ecom_brand', 't.name', 'ASC', NULL, NULL, NULL)->d;
?>
<div class="pure-form">
  <input id="find_name" type="text" style="width: 250px;" placeholder="{Search}" onkeypress="if(event.which == 13) find();">
  <select id="find_type">
    <option value="0">All</option>
    <option value="1">Available</option>
    <option value="2">Unavailable</option>
    <option value="3">Out of stock</option>
  </select>
  <button type="submit" class="pure-button pure-button-primary" onclick="find();">Go</button>
</div>
<div>&nbsp;</div>
<button onclick="Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=index_product&pg=' + __data.p);" class="pure-button pure-button-primary">New Product</button>
<table class="pure-table pure_table_extra" cellpadding=0 cellspacing=0>
  <thead>
    <tr>
      <th class="ui-widget-header" style="width: 120px;" onclick="return set_order('name');">Product</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('category_id');">Category</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('brand_id');">Brand</th>
      <th class="ui-widget-header" style="width: 50px;" onclick="return set_order('curr');">Curr</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('price');">Price</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('enabled_member');">Member -%</th>
      <th class="ui-widget-header" style="width: 80px;" onclick="return set_order('alert__');">Stock</th>
      <th class="ui-widget-header" style="width: 120px;" onclick="return set_order('status');">Availability</th>
      <th class="ui-widget-header" style="width: 60px;">&nbsp;</th>
    </tr>
  </thead>
  <tbody id="data_body"></tbody>
</table>
<div>&nbsp;</div>
<div id="pagination"></div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __categories = JSON.parse('<?php echo addslashes(json_encode($categories)); ?>');
  var __brands = JSON.parse('<?php echo addslashes(json_encode($brands)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __search = JSON.parse('<?php echo addslashes(json_encode($search)); ?>');
  
  $(function(){
    render();
  });

  function render() {
    $('#pagination').pagination({
      items: __data.t,
      itemsOnPage: __data.s,
      currentPage: __data.p,
      cssStyle: 'compact-theme',
      onPageClick: function(pageNumber, event) {
        return Url.redirect(__redmd, __sys + '.php?i=' + __id + '&pg=' + pageNumber + '&o=' + __data.o + '&q=' + __data.q + '&search=' + Utils.encodeURI(JSON.stringify(__search)));
      }
    });
    render_data();
  };
  
  function render_data() {
    Url.insert_param('o', __data.o);
    Url.insert_param('q', __data.q);
    Url.insert_param('search', Utils.encodeURI(JSON.stringify(__search)));

    if (__search.type) {
      $('#find_type').val(__search.type);
    }
    if (__search.phrase) {
      $('#find_name').val(__search.phrase);
    }
    
    $('#data_body').empty();
    for (var idx in __data.d) {
      var itm = __data.d[idx];
      $('#data_body').append(
        '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td>' + itm.name + '</td>' +
          '<td>' + __to_name(itm.category_id, __categories) + '</td>' +
          '<td>' + __to_name(itm.brand_id, __brands) + '</td>' +
          '<td>' + itm.curr + '</td>' +
          '<td>' + accounting.formatMoney(itm.price) + '</td>' +
          '<td class="smaller"><input id="disc_' + itm.id + '" onclick="set_disc(' + itm.id + ', this.checked);" type="checkbox" ' + ((itm.enabled_member == 1) ? 'checked="checked"' : '' ) + '" /><label id="disc_txt_' + itm.id + '" for="disc_' + itm.id + '" style="margin-right: 0;">' + ((itm.enabled_member == 1) ? 'Yes' : 'No') + '</label></td>' +
          '<td' + ((itm.alert__ == 1) ? ' style="color: #ff0000"' : '') + '>' + itm.stock + '</td>' +
          '<td class="smaller"><input id="avail_' + itm.id + '" onclick="set_avail(' + itm.id + ', this.checked);" type="checkbox" ' + ((itm.status == 1) ? 'checked="checked"' : '' ) + '" /><label id="avail_txt_' + itm.id + '" for="avail_' + itm.id + '" style="margin-right: 0;">' + ((itm.status == 1) ? 'Available' : 'Unavailable') + '</label></td>' +
          '<td>' + 
            '<span style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-pencil" onclick="Url.redirect(' + __redmd + ', \'' + __sys + '.php?i=' + __id + '&__file=index_product&id=' + itm.id + '&pg=' + __data.p + '\');"></span>' +
            '<span style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="delete_obj(' + itm.id + ');"></span>' +
          '</td>' + 
        '</tr>'
      );
    }
    if (__data.d.length == 0) {
      $('#data_body').append('<tr class="pure-table-even"><td colspan=9>None</td></tr>');
    }
    $('#data_body input[type=checkbox]').button();
  };

  function __get_search() {
    return {
      type: $('#find_type option:selected').val(),
      phrase: $('#find_name').val()
    };
  };
  
  function delete_obj(id) {
    var req = Utils.get_by_id(id, __data.d);
    req.__pg = __data.p;
    req.__o = __data.o;
    req.__q = __data.q;
    Ajax.request(
      __requrl + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        render();
      },
      { confirm: 1 }
    );
  };

  function set_avail(id, avail) {
    if (avail) {
      $('#avail_' + id)[0].checked = true;
      $('#avail_txt_' + id).empty();
      $('#avail_txt_' + id).append('<span class="ui-button-text">Available</span>');
      $('#avail_txt_' + id).addClass('ui-state-active');
    } else {
      $('#avail_' + id)[0].checked = false;
      $('#avail_txt_' + id).empty();
      $('#avail_txt_' + id).append('<span class="ui-button-text">Unavailable</span>');
      $('#avail_txt_' + id).removeClass('ui-state-active');
    }
    var req = Utils.get_by_id(id, __data.d);
    req.status = avail ? 1 : 0;
    Ajax.request(
      __requrl.replace(__file, 'index_product') + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
      },
      { silent: 1 }
    );
  };

  function set_disc(id, disc) {
    if (disc) {
      $('#disc_' + id)[0].checked = true;
      $('#disc_txt_' + id).empty();
      $('#disc_txt_' + id).append('<span class="ui-button-text">Yes</span>');
      $('#disc_txt_' + id).addClass('ui-state-active');
    } else {
      $('#disc_' + id)[0].checked = false;
      $('#disc_txt_' + id).empty();
      $('#disc_txt_' + id).append('<span class="ui-button-text">No</span>');
      $('#disc_txt_' + id).removeClass('ui-state-active');
    }
    var req = Utils.get_by_id(id, __data.d);
    req.enabled_member = disc ? 1 : 0;
    Ajax.request(
      __requrl.replace(__file, 'index_product') + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
      },
      { silent: 1 }
    );
  };

  function set_order(o) {
    var req = {
      q: (__data.q) == 'ASC' ? 'DESC' : 'ASC',
      o: o,
      pg: __data.p,
      search: __search
    };
    Ajax.request(
      __requrl + 'get_objs',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        render();
      },
      null
    );
  };

  function find() {
    __search = __get_search();
    
    var req = {
      q: __data.q,
      o: __data.o,
      pg: __data.p,
      search: __search
    };
    Ajax.request(
      __requrl + 'get_objs',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        render();
      },
      null
    );
  };

  function __to_name(id, data) {
    for (var idx in data) {
      var itm = data[idx];
      if (itm.id == id) {
        return itm.name;
      }
    }
    return '';
  };
  /*]]>*/
</script>